<script setup lang="ts">
import { commonEnums } from '@/enums';
import { Session } from '@/utils/storage';
import { onBeforeRouteUpdate } from 'vue-router';

interface HistoryMenuItem {
  title: string;
  path: string;
}

const route = useRoute();
const router = useRouter();
const state = reactive<{
  historyMenu: HistoryMenuItem[];
}>({
  historyMenu: [
    {
      title: '工作台',
      path: '/admin/home',
    },
  ],
});

const removeItem = (item: HistoryMenuItem) => {
  const index = state.historyMenu.findIndex((el: HistoryMenuItem) => el.path === item.path);
  if (item.path === route.path) {
    if (index === state.historyMenu.length - 1) router.push(state.historyMenu[index - 1]);
    else router.push(state.historyMenu[index + 1]);
    state.historyMenu.splice(index, 1);
    Session.setItem(commonEnums.HISTORY_MENU, state.historyMenu);
  } else {
    state.historyMenu.splice(index, 1);
    Session.setItem(commonEnums.HISTORY_MENU, state.historyMenu);
  }
};

onMounted(() => {
  state.historyMenu = Session.getItem(commonEnums.HISTORY_MENU) ?? state.historyMenu;
  if (state.historyMenu.length === 1) router.push(state.historyMenu[0].path);
});

onBeforeRouteUpdate((to) => {
  const item = {
    title: to.meta.title as string,
    path: to.path,
  };
  const flag = state.historyMenu.some((item: HistoryMenuItem) => item.path === to.path);
  if (flag) return;
  state.historyMenu.push(item);
  Session.setItem(commonEnums.HISTORY_MENU, state.historyMenu);
});
</script>

<template>
  <el-scrollbar>
    <div class="border-b border-gray-200 px-4 py-2 whitespace-nowrap" style="width: calc(100vw - 13rem)">
      <div class="inline-block mr-1" v-for="item in state.historyMenu" :key="item.path">
        <div
          :class="$route.path === item.path ? 'active' : ''"
          class="text-sm flex items-center bg-white py-1 px-2 text-gray-600 border border-solid border-gray-200 hover:border-white rounded-sm hover:bg-violet-500 hover:text-white duration-300 hover:cursor-pointer"
        >
          <router-link :to="item.path">
            <span class="mr-1">{{ item.title }}</span>
          </router-link>
          <MyImg
            v-if="item.path !== '/admin/home'"
            name="ele-Close"
            class="hover:bg-violet-300 hover:rounded-full"
            @click.stop="removeItem(item)"
          />
        </div>
      </div>
    </div>
  </el-scrollbar>
</template>

<style scoped lang="scss">
.active {
  @apply text-white bg-violet-500;
}
</style>
